<?php
namespace dreamphp\core;

class Db
{
	//单例模式，就是只有一个实例，基础课程我们讲过了，这里就不再讲了，直接实现
	private static $instance = null;
	private static $connection = null;
	
	private function __construct()
	{
		try {
			$dsn = sprintf("mysql:host=%s;dbname=%s;charset=%s", DB_HOST, DB_NAME, 'utf8');
			$option = [\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC];
			self::$connection = new \PDO($dsn, DB_USER, DB_PASS, $option);
		}catch (\PDOException $e) {
			$error = (string)$e->getMessage();
			throw new \PDOException($e->getMessage());
		}
	}
	
	private function __clone()
	{}
	
	public static function getInstance()
	{
		if (!self::$instance instanceof slef) {
			self::$instance = new self();
		}
		return self::$instance;
	}
	
	//这里我只封装一个查询单条数据库的方法，查询多条、添加、删除修改方法大家自己实现
	public static function find($sql)
	{
		return self::$connection->query($sql)->fetch();
	}
}